const redisClient = require("@/redis/redis-client");
const redisKeysConstant = require("@/constants/redis-keys.constant");
const fileBusinessService = require("@/common/file-business.service");
const BaseTaskScheduler = require("./base-task-scheduler");

// cron规则, 每5分钟执行一次
const CRON_PATTERN = "*/5 * * * *";

// 数据库备份
const redisDeleteExpiredPreviewFiles = new BaseTaskScheduler();
/**
 * 任务运行
 */
const TaskHandler = async () => {
	try {
		console.log("定时任务执行中-删除redis中过期的预览文件");
		const keys = (await redisClient.get(redisKeysConstant.filePreviewKeys)) || [];
        const expiredKeys = [];
		for (let i = 0; i < keys.length; i++) {
			const key = keys[i];
			const itemData = await redisClient.get(redisKeysConstant.filePreview(key)); // 在redis中查询文件过期信息
            if (!itemData) {
                expiredKeys.push(keys[i]);   
            } else {
                // 如果过期了，直接删除
                if (itemData.extTime && itemData.extTime && Date.now() > itemData.extTime) {
                    await fileBusinessService.deletePreviewExpiredFile(key); // 删除redis中缓存数据
                    console.log(`redis过期的附件: ${key} 已被删除`);
                    expiredKeys.push(keys[i])
                }
            }	
		}

        // 通过过期的keys
        if (expiredKeys.length > 0) {
            const newKeys = keys.filter(k => !expiredKeys.includes(k));
            await redisClient.set(redisKeysConstant.filePreviewKeys, newKeys);
        }
	} catch (error) {
		console.log("定时删除redis中过期的预览文件异常: ", error);
	}
};

// 创建一个30分钟执行一次的任务
redisDeleteExpiredPreviewFiles.createJob(CRON_PATTERN, TaskHandler, { initExecute: true });

module.exports = redisDeleteExpiredPreviewFiles;
